package net.xumf.web.aop;

import net.xumf.domain.master.SystemLog;
import net.xumf.domain.master.SystemUser;
import net.xumf.service.master.SystemLogService;
import net.xumf.support.aop.LogMonitor;
import net.xumf.support.auth.CurrentUser;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class PersistenceLogMonitor extends LogMonitor {

    @Autowired
    private SystemLogService systemLogService;

    @Override
    protected void logEvent(EventParameter eventParameter) {
        super.logEvent(eventParameter);
        final HttpServletRequest req =
                ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        if ("/login/action".equals(req.getRequestURI())) {
            return;
        }
        SystemUser systemUser = CurrentUser.instance().get();
        if (null != systemUser) {
            final SystemLog log = SystemLog.builder()
                    .source(eventParameter.getSource())
                    .username(systemUser.getUsername())
                    .userId(systemUser.getId())
                    .message(eventParameter.toString())
                    .level(eventParameter.getLevel())
                    .url(req.getRequestURL().toString())
                    .build();
            systemLogService.add(log);
        }
    }
}
